<?php namespace Common\Model;

use Hdphp\Model\Model;

//分类表
class Cate extends Model{
	//定义模型
	protected $table = "category";
	//自动验证
	protected $validate = array(
		array('cname','required','分类名称不能为空',3,3),
		array('cname','maxlen:50','分类名称不能大于50个字',3,3),
		array('csort','required','分类排序不能为空',3,3),
	);

	//添加分类
	public function store(){
		if ($this->create()) {
			$cateArr=explode('|',Q('post.cname'));
			foreach ($cateArr as $v) {
				$this->add(array(
					'cname'=>$v,
					'csort'=>Q('post.csort'),
					'pid'=>Q('post.pid'),
				));
			}
			Cache::del('cateTree');
			Cache::del('cateData');
			return true;
		}
		return false;
	}

	//获得除了自己和自己子集的所有数据
	public function notMy($cid){
		//获得自己的所有子集
		$cids=$this->getSon($cid);
		//压入自己
		$cids[]=$cid;
		return $this->where("cid not in (".implode(',',$cids).")")->get();
	}

	//获得自己的子集
	public function getSon($cid){
		$tmp=[];
		foreach ($this->get() as $value) {
			if ($value['pid']==$cid) {
				$tmp[]=$value['cid'];
				$tmp=array_merge($tmp,$this->getSon($value['cid']));
			}
		}
		return $tmp;
	}

	//编辑分类
	public function edit(){
		if ($this->create()) {
			$this->save();
			return true;
		}
		return false;
	}

}